package com.luoy.netty.echo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

/**
 * @author LUOYUAN
 * @create 2019-07-08-14:20
 */

public class EchoServer {

    private final  int port;

    public EchoServer(int port) {
        this.port = port;
    }

    public static void main (String[] args) throws InterruptedException{
        int port = 6789;
        EchoServer echoServer = new EchoServer(port);
        System.out.println("服务器即将启动");
        echoServer.start();
        System.out.println("服务器即将关闭");
    }

    public void start() throws InterruptedException{

        final EchoServerHandler s = new EchoServerHandler();
        //线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workGroup = new NioEventLoopGroup();
        try {
            //服务器端启动必备
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup,workGroup)
                    //使用NIO进行通讯
             .channel(NioServerSocketChannel.class)
                    //指明服务器监听端口
             .localAddress(new InetSocketAddress(port))
                    //接收到连接请求，新启一个socket通信，也就是channel.每个channel有自己的事件的handler
             .childHandler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(s);
                 }
             });

            //绑定到端口，阻塞等待直到连接完成
            ChannelFuture f = b.bind().sync();
            //阻塞，直到channel关闭
            f.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully().sync();
            workGroup.shutdownGracefully().sync();
        }
    }
}
